package com.boottest.better.test.viewresolver;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;

public class MyViewResolver implements ViewResolver, ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public View resolveViewName(String viewName, Locale locale) throws Exception {

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();

        String requestURI = request.getRequestURI();

        for (String url : resolverMap.keySet()) {

            if (requestURI.contains(url)) {
                return applicationContext.getBean(resolverMap.get(url).getClass()).resolveViewName(viewName, locale);
            }

        }

        return defaultViewResolver.resolveViewName(viewName, locale);
    }

    private Map<String, ViewResolver> resolverMap = new HashMap<String, ViewResolver>();

    public Map<String, ViewResolver> getResolverMap() {
        return resolverMap;
    }

    public void setResolverMap(Map<String, ViewResolver> resolverMap) {
        this.resolverMap = resolverMap;
    }

    private ViewResolver defaultViewResolver = null;

    public ViewResolver getDefaultViewResolver() {
        return defaultViewResolver;
    }

    public void setDefaultViewResolver(ViewResolver defaultViewResolver) {
        this.defaultViewResolver = defaultViewResolver;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        this.applicationContext = applicationContext;

    }

}
